﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CustomORM
{
    public static class SqlBuilder
    {
        public static string CommaSeparate(List<string> items)
        {
            var stringBuilder = new StringBuilder();
            foreach (var item in items)
            {
                stringBuilder.AppendFormat("{0}, ", item);
            }
            if (stringBuilder.Length >= 2)
            {
                stringBuilder.Remove(stringBuilder.Length - 2, 2);
            }

            return stringBuilder.ToString();
        }

        public static string CommaSeparateFields(List<string> fieldNames, string tableAlias)
        {
            var stringBuilder = new StringBuilder();
            foreach (var fieldName in fieldNames)
            {
                stringBuilder.AppendFormat("{0}.{1} as {0}{1}, {2}", tableAlias, fieldName, Environment.NewLine);
            }

            var lengthToRemove = 2 + Environment.NewLine.Length;
            if (stringBuilder.Length >= lengthToRemove)
            {
                stringBuilder.Remove(stringBuilder.Length - lengthToRemove, lengthToRemove);
            }

            return stringBuilder.ToString();
        }

        public static string FormatSelectHeader(string selectFields, string tableName, string mainAlias)
        {
            var selectStatement = string.Format("SELECT {0} {3}FROM {1} {2} ", selectFields, tableName, mainAlias, Environment.NewLine);
            return selectStatement;
        }

        public static string CommaSeparateFields(List<string> fieldNames, string tableAlias, List<string> fieldNamesUnique)
        {
            if(fieldNames.Count != fieldNamesUnique.Count)
            {
                throw new Exception("fieldNames count and fieldNamesUnique MUST be the same");
            }

            var stringBuilder = new StringBuilder();
            for (int i = 0; i < fieldNames.Count; i++)
            {
                stringBuilder.AppendFormat("{0}.{1} as {2}, {3}", tableAlias, fieldNames[i], fieldNamesUnique[i], Environment.NewLine);
            }

            var lengthToRemove = 2 + Environment.NewLine.Length;
            if (stringBuilder.Length >= lengthToRemove)
            {
                stringBuilder.Remove(stringBuilder.Length - lengthToRemove, lengthToRemove);
            }

            return stringBuilder.ToString();
        }
    }
}